// @algorithm @lc id=1000301 lang=cpp
// @title pOCWxh

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode *pruneTree(TreeNode *root) {
        if (root == nullptr) {
            return nullptr;
        }
        TreeNode *newHead = new TreeNode(1, root, nullptr);
        dfs(newHead);
        return newHead->left;
    }

    bool dfs(TreeNode *root) {
        if (root == nullptr) {
            return true;
        }
        bool leftSonFlag = dfs(root->left);
        bool rightSonFlag = dfs(root->right);
        if (leftSonFlag && root->left) {
            root->left = nullptr;
        }
        if (rightSonFlag && root->right) {
            root->right = nullptr;
        }
        if (root->val == 1) {
            return false;
        }
        else {
            return leftSonFlag && rightSonFlag;
        }
    }
};